package cn.op.portal.filter;

import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.Filter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class StaticUriFilter implements Filter {

	/**
	 * Constructor of the object.
	 */
	public StaticUriFilter() {
		super();
	}

	private FilterConfig filterConfig;

	// Handle the passed-in FilterConfig	
	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
	}

	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain filterChain)

	{
		try {
			HttpServletRequest request = (HttpServletRequest) req;
			HttpServletResponse response = (HttpServletResponse) res;
			HttpSession session = request.getSession();

			
			// 这里放到达目的地前(进入)处理代码
			if( request.getPathInfo()!=null){
				String uri = request.getPathInfo().toString();
				System.out.println("-----" + uri);
			}

//			String fileName = uri.substring(uri.lastIndexOf("/"));
//			fileName = new String(fileName.getBytes("iso8859-1"), "utf-8");
//			fileName = request.getRealPath("/images" + fileName);
//			fileName = URLDecoder.decode(fileName);
//			System.out.println(fileName);
//			File file = new File(fileName);
//			System.out.println(file.exists());


			
			
			filterChain.doFilter(new UrlDecodingRequest(request), response);
			

		} catch (IOException e) {
			e.printStackTrace();
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		// Just puts "destroy" string in log
		// Put your code here
	}
	
	class UrlDecodingRequest extends HttpServletRequestWrapper{

		private HttpServletRequest request;
		
		public UrlDecodingRequest(HttpServletRequest request) {
			super(request);
			this.request = request;
		}


		@Override
		public StringBuffer getRequestURL() {
			String url = request.getRequestURL().toString();
			if(null==url) {
				return null;
			}
			try {
				url = URLDecoder.decode(url.toString());
				return new StringBuffer(url);
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}
	}

}
